﻿using System;
using FireStarterModeller.BO;
using Habanero.Util;

namespace FireStarterModeller.Logic
{
    public static class DomainModelVersioner
    {
        public static void UpdateSolution(DMSolution solution)
        {
            foreach (var dmClass in solution.AllClasses)
            {
                if (dmClass.HasSuperClass)
                {
                    UpdateInheritanceRelationship(dmClass.InheritanceSuperClassRelationship);
                }
            }
        }
        
        private static void UpdateInheritanceRelationship(DMInheritanceRelationship inheritanceSuperClassRelationship)
        {
            if (inheritanceSuperClassRelationship == null) return;
            if (inheritanceSuperClassRelationship.IdentityProperty != null) return;
            var identity = inheritanceSuperClassRelationship.Identity;
            if (String.IsNullOrEmpty(identity)) return;
            var subClass = inheritanceSuperClassRelationship.SubClass;
            Guid guidIdentity;
            DMProperty identityProperty = null;
            if (StringUtilities.GuidTryParse(identity, out guidIdentity))
            {
                identityProperty = subClass.AllProperties.Find(guidIdentity);
            }
            if (identityProperty == null)
            {
                identityProperty = (DMProperty) subClass.GetDMProperty(identity);
            }
            if (identityProperty != null)
            {
                inheritanceSuperClassRelationship.IdentityProperty = identityProperty;
                inheritanceSuperClassRelationship.Identity = identityProperty.PropertyName;
            }
        }
    }
}